package com.wlld.myjecs.controller;

import com.alibaba.fastjson.JSON;
import com.wlld.myjecs.Session.WlldSession;
import com.wlld.myjecs.config.ErrorCode;
import com.wlld.myjecs.mesEntity.Response;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @param
 * @DATA
 * @Author LiDaPeng
 * @Description
 */
public class UserFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //跳过API文档路径
        String url = request.getRequestURI();
        if (url.equals("")||url.equals("/")) {
            response.sendRedirect("index");
        }
        if (url.contains("doc.html")) {
            return true;
        }
        if (url.contains("index")) {
            return true;
        }
        //简单处理一下 只要有token就认为登录过
        String token = response.getHeader("tokenID");
        System.out.println(token);
        if (token != null) {
            return true;
        }
        if (WlldSession.getSESSION().getValue(response, "myID") != null) {
            return true;
        } else {
            response.setCharacterEncoding("utf-8");
            PrintWriter printWriter = response.getWriter();
            Response res = new Response();
            res.setError(ErrorCode.InvalidLogin.getError());
            res.setErrorMessage(ErrorCode.InvalidLogin.getErrorMessage());
            printWriter.print(JSON.toJSONString(res));
            System.out.println("地址被拦:"+url);
            return false;
        }
    }
}
